import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:hello_flutter/container/clip.dart';
import 'package:hello_flutter/container/container.dart';
import 'package:hello_flutter/container/decorated_box.dart';
import 'package:hello_flutter/container/fitted_box.dart';
import 'package:hello_flutter/container/index.dart';
import 'package:hello_flutter/container/padding.dart';
import 'package:hello_flutter/container/scaffold.dart';
import 'package:hello_flutter/container/transform.dart';
import 'package:hello_flutter/layout/align.dart';
import 'package:hello_flutter/layout/flex.dart';
import 'package:hello_flutter/layout/index.dart';
import 'package:hello_flutter/layout/constrained_box.dart';
import 'package:hello_flutter/layout/sized_box.dart';
import 'package:hello_flutter/layout/stack_and_positioned.dart';
import 'package:hello_flutter/layout/wrap.dart';
import 'package:hello_flutter/pub_test.dart';
import 'package:hello_flutter/route.dart';
import 'package:hello_flutter/scrollable/animated_list.dart';
import 'package:hello_flutter/scrollable/custom_scroll_view_and_slivers.dart';
import 'package:hello_flutter/scrollable/custom_sliver.dart';
import 'package:hello_flutter/scrollable/grid_view.dart';
import 'package:hello_flutter/scrollable/grid_view_infinite.dart';
import 'package:hello_flutter/scrollable/index.dart';
import 'package:hello_flutter/scrollable/list_view.dart';
import 'package:hello_flutter/scrollable/nested_scroll_view.dart';
import 'package:hello_flutter/scrollable/page_view_and_cache.dart';
import 'package:hello_flutter/scrollable/scroll_listen_and_control.dart';
import 'package:hello_flutter/scrollable/single_child_scroll_View.dart';
import 'package:hello_flutter/scrollable/tab_bar_view.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      initialRoute: '/',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // TRY THIS: Try running your application with "flutter run". You'll see
        // the application has a purple toolbar. Then, without quitting the app,
        // try changing the seedColor in the colorScheme below to Colors.green
        // and then invoke "hot reload" (save your changes or press the "hot
        // reload" button in a Flutter-supported IDE, or press "r" if you used
        // the command line to start the app).
        //
        // Notice that the counter didn't reset back to zero; the application
        // state is not lost during the reload. To reset the state, use hot
        // restart instead.
        //
        // This works for code too, not just values: Most code changes can be
        // tested with just a hot reload.
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      routes: {
        '/': (context) => const MyHomePage(title: 'Flutter Demo Home Page'),
        'newRoute': (context) => const NewRoute(),
        'tipRoute': (context) => TipRoute(
              text: ModalRoute.of(context)!.settings.arguments! as String,
            ),

        // region 布局类组件
        '/layout': (context) => const LayoutIndexWidget(),
        '/layout/constrained_box': (context) => const ConstrainedBoxWidget(),
        '/layout/sized_box': (context) => const SizedBoxWidget(),
        '/layout/flex': (context) => const FlexWidget(),
        '/layout/wrap': (context) => const WrapWidget(),
        '/layout/stack': (context) => const StackAndPositionedWidget(),
        '/layout/align': (context) => const AlignWidget(),
        // endregion

        // region 容器类组件
        '/container': (context) => const ContainerIndexWidget(),
        '/container/padding': (context) => const PaddingWidget(),
        '/container/decorated_box': (context) => const DecoratedBoxWidget(),
        '/container/transform': (context) => const TransformWidget(),
        '/container/container': (context) => const ContainerWidget(),
        '/container/clip': (context) => const ClipWidget(),
        '/container/fitted_box': (context) => const FittedBoxWidget(),
        '/container/scaffold': (context) => const ScaffoldWidget(),
        // endregion

        // region 可滚动组件
        '/scrollable': (context) => const ScrollableIndexWidget(),
        '/scrollable/single_child_scroll_View': (context) =>
            const SingleChildScrollViewWidget(),
        '/scrollable/list_view': (context) => const ListViewWidget(),
        '/scrollable/scroll_listen_and_control': (context) =>
            const ScrollListenAndControlWidget(),
        '/scrollable/animated_list': (context) => const AnimatedListWidget(),
        '/scrollable/grid_view': (context) => const GridViewWidget(),
        '/scrollable/grid_view_infinite': (context) =>
            const InfiniteGridViewWidget(),
        '/scrollable/page_view_and_cache': (context) => PageViewAndCacheWidget(
              title: ModalRoute.of(context)!.settings.arguments! as String,
            ),
        '/scrollable/tab_bar_view': (context) => const TabBarViewWidget(),
        '/scrollable/custom_scroll_view_and_slivers': (context) => const CustomScrollViewAndSliversWidget(),
        '/scrollable/custom_scroll_view_and_slivers/CustomScrollView': (context) => const CustomScrollViewWidget(),
        '/scrollable/custom_scroll_view_and_slivers/Slivers': (context) => const SliversWidget(),
        '/scrollable/custom_scroll_view_and_slivers/SliverToBoxAdapter': (context) => const SliverToBoxAdapterWidget(),
        '/scrollable/custom_scroll_view_and_slivers/SliverPersistentHeader': (context) => const SliverPersistentHeaderWidget(),
        '/scrollable/custom_sliver': (context) => const CustomSliverWidget(),
        '/scrollable/nested_scroll_view': (context) => const NestedScrollViewWidget(),
        // endregion
      },
      // home: const MyHomePage(title: 'Flutter Demo Home Page'),
      // home: const CounterWidget(),
      // home: const GetStateObjectRoute(),
      // home: const TapboxA(),
      // home: const TapboxBParentWidget(),
      // home: const TapboxCParentWidget(),
    );
  }
}

class MyCupertinoApp extends StatelessWidget {
  const MyCupertinoApp({super.key});

  @override
  Widget build(BuildContext context) {
    return CupertinoApp(
      home: CupertinoPageScaffold(
        navigationBar: const CupertinoNavigationBar(
          middle: Text(
            "Cupertino Demo",
          ),
        ),
        child: Center(
          child: CupertinoButton(
            color: CupertinoColors.activeBlue,
            onPressed: () {
              print('Click press');
            },
            child: const Text(
              "Press",
            ),
          ),
        ),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // TRY THIS: Try changing the color here to a specific color (to
        // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
        // change color while the other colors stay the same.
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            // Column is also a layout widget. It takes a list of children and
            // arranges them vertically. By default, it sizes itself to fit its
            // children horizontally, and tries to be as tall as its parent.
            //
            // Column has various properties to control how it sizes itself and
            // how it positions its children. Here we use mainAxisAlignment to
            // center the children vertically; the main axis here is the vertical
            // axis because Columns are vertical (the cross axis would be
            // horizontal).
            //
            // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
            // action in the IDE, or press "p" in the console), to see the
            // wireframe for each widget.
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Text(
                'You have clicked the button this many times:',
              ),
              Text(
                '$_counter',
                style: Theme.of(context).textTheme.headlineMedium,
              ),
              TextButton(
                child: const Text("open new route with push"),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) {
                      return const NewRoute();
                    }),
                  );
                },
              ),
              TextButton(
                child: const Text("open new route with pushNamed"),
                onPressed: () {
                  Navigator.pushNamed(context, 'newRoute');
                },
              ),
              TextButton(
                child: const Text("open tip route with push"),
                onPressed: () async {
                  var result = await Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) {
                      return const TipRoute(text: "我是传入的提示内容1");
                    }),
                  );

                  print('TipRoute返回数据: $result');
                },
              ),
              TextButton(
                child: const Text("open tip route with pushNamed"),
                onPressed: () async {
                  var result = await Navigator.pushNamed(context, 'tipRoute',
                      arguments: '我是传入的提示内容2');

                  print('TipRoute返回数据: $result');
                },
              ),
              const RandomWordsWidget(),
              TextButton(
                onPressed: () => Navigator.of(context).pushNamed('/layout'),
                child: const Text('布局类组件'),
              ),
              TextButton(
                onPressed: () => Navigator.of(context).pushNamed('/container'),
                child: const Text('容器类组件'),
              ),
              TextButton(
                onPressed: () => Navigator.of(context).pushNamed('/scrollable'),
                child: const Text('可滚动组件'),
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

class NewRoute extends StatelessWidget {
  const NewRoute({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("New Route"),
      ),
      body: const Center(
        child: Text("This is new route"),
      ),
    );
  }
}

class CounterWidget extends StatefulWidget {
  const CounterWidget({super.key, this.initValue = 0});

  final int initValue;

  @override
  _CounterWidgetState createState() => _CounterWidgetState();
}

class _CounterWidgetState extends State<CounterWidget> {
  int _counter = 0;

  @override
  void initState() {
    super.initState();
    _counter = widget.initValue;
    print('initState');
  }

  @override
  Widget build(BuildContext context) {
    print('build');
    return Scaffold(
      body: Center(
        child: TextButton(
          child: Text(
            '$_counter',
            style: Theme.of(context).textTheme.headlineMedium,
          ),
          onPressed: () => setState(() {
            ++_counter;
          }),
        ),
      ),
    );
  }

  @override
  void didUpdateWidget(covariant CounterWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    print('didUpdateWidget');
  }

  @override
  void activate() {
    super.activate();
    print('active');
  }

  @override
  void deactivate() {
    super.deactivate();
    print('deactivate');
  }

  @override
  void dispose() {
    super.dispose();
    print('dispose');
  }

  @override
  void reassemble() {
    super.reassemble();
    print('reassemble');
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print('didChangeDependencies');
  }
}

class GetStateObjectRoute extends StatefulWidget {
  const GetStateObjectRoute({super.key});

  @override
  _GetStateObjectRouteState createState() => _GetStateObjectRouteState();
}

class _GetStateObjectRouteState extends State<GetStateObjectRoute> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Builder(builder: (context) {
              return ElevatedButton(
                  onPressed: () {
                    ScaffoldState state =
                        context.findAncestorStateOfType<ScaffoldState>()!;
                    state.openDrawer();
                  },
                  child: const Text('打开抽屉菜单-方式1'));
            }),
            Builder(builder: (context) {
              return ElevatedButton(
                  onPressed: () {
                    ScaffoldState state = Scaffold.of(context);
                    state.openDrawer();
                  },
                  child: const Text('打开抽屉菜单-方式2'));
            }),
            Builder(builder: (context) {
              return ElevatedButton(
                  onPressed: () {
                    ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('Hello SnackBar')));
                  },
                  child: const Text('显示SnackBar'));
            }),
          ],
        ),
      ),
      drawer: const Drawer(),
    );
  }
}

class CustomWidget extends LeafRenderObjectWidget {
  const CustomWidget({super.key});

  @override
  RenderObject createRenderObject(BuildContext context) {
    return CustomRenderObject();
  }

  @override
  void updateRenderObject(
      BuildContext context, covariant RenderObject renderObject) {
    super.updateRenderObject(context, renderObject);
  }
}

class CustomRenderObject extends RenderBox {
  @override
  void performLayout() {
    // 实现布局逻辑
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    // 实现绘制
  }
}

class TapboxA extends StatefulWidget {
  const TapboxA({super.key});

  @override
  State<TapboxA> createState() => _TapboxAState();
}

class _TapboxAState extends State<TapboxA> {
  bool _active = false;

  void _handleTap() {
    setState(() {
      _active = !_active;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: _handleTap,
        child: Center(
          child: Container(
            width: 200,
            height: 200,
            decoration: BoxDecoration(
                color: _active ? Colors.lightGreen[700] : Colors.grey[600]),
            child: Center(
              child: Text(
                _active ? 'ActiveA' : 'InactiveA',
                style: const TextStyle(fontSize: 32, color: Colors.white),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class TapboxB extends StatelessWidget {
  const TapboxB({super.key, this.active = false, required this.onChanged});

  final bool active;
  final ValueChanged<bool> onChanged;

  void _handleTap() {
    onChanged(!active);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _handleTap,
      child: Container(
        width: 200,
        height: 200,
        decoration: BoxDecoration(
            color: active ? Colors.lightGreen[700] : Colors.grey[600]),
        child: Center(
          child: Text(
            active ? 'ActiveB' : 'InactiveB',
            style: const TextStyle(fontSize: 32, color: Colors.white),
          ),
        ),
      ),
    );
  }
}

class TapboxBParentWidget extends StatefulWidget {
  const TapboxBParentWidget({super.key});

  @override
  State<TapboxBParentWidget> createState() => _TapboxBParentWidgetState();
}

class _TapboxBParentWidgetState extends State<TapboxBParentWidget> {
  bool _active = false;

  void _onChange(bool changed) {
    setState(() {
      _active = changed;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: TapboxB(active: _active, onChanged: _onChange),
      ),
    );
  }
}

class TapboxC extends StatefulWidget {
  const TapboxC({super.key, this.active = false, required this.onChanged});

  final bool active;
  final ValueChanged<bool> onChanged;

  @override
  State<TapboxC> createState() => _TapboxCState();
}

class _TapboxCState extends State<TapboxC> {
  bool _highlight = false;

  void _handleTapDown(TapDownDetails details) {
    setState(() {
      _highlight = true;
    });
  }

  void _handleTapUp(TapUpDetails details) {
    setState(() {
      _highlight = false;
    });
  }

  void _handleTapCancel() {
    setState(() {
      _highlight = false;
    });
  }

  void _handleTap() {
    widget.onChanged(!widget.active);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTapDown: _handleTapDown,
      onTapUp: _handleTapUp,
      onTapCancel: _handleTapCancel,
      onTap: _handleTap,
      child: Container(
        width: 200,
        height: 200,
        decoration: BoxDecoration(
            color: widget.active ? Colors.lightGreen[700] : Colors.grey[600],
            border: _highlight
                ? Border.all(color: Colors.teal[700]!, width: 10)
                : null),
        child: Center(
          child: Text(
            widget.active ? 'ActiveC' : 'InactiveC',
            style: const TextStyle(fontSize: 32, color: Colors.white),
          ),
        ),
      ),
    );
  }
}

class TapboxCParentWidget extends StatefulWidget {
  const TapboxCParentWidget({super.key});

  @override
  State<TapboxCParentWidget> createState() => _TapboxCParentWidgetState();
}

class _TapboxCParentWidgetState extends State<TapboxCParentWidget> {
  bool _active = false;

  void _onChange(bool changed) {
    setState(() {
      _active = changed;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: TapboxC(active: _active, onChanged: _onChange),
      ),
    );
  }
}
